<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="前端,前端基础,IIFE," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Immediately-invoked Function Expression（IIFE，立即调用函数），简单的理解就是定义完成函数之后立即执行。因此有时候也会被称为“自执行的匿名函数”（self-executing anonymous function）。
IIFE的叫法最早见于Ben Alman的文章。文章中Ben Alman 已经解释得很清楚了，希望定义自执行函数式常见的语法错误有两种：
1">
<meta property="og:type" content="article">
<meta property="og:title" content="Javascript知识点：IIFE - 立即调用函数">
<meta property="og:url" content="http://jiji262.github.io/2016/04/25/2016-04-08-Javascript-IIFE/index.html">
<meta property="og:site_name" content="令狐葱@前端笔记">
<meta property="og:description" content="Immediately-invoked Function Expression（IIFE，立即调用函数），简单的理解就是定义完成函数之后立即执行。因此有时候也会被称为“自执行的匿名函数”（self-executing anonymous function）。
IIFE的叫法最早见于Ben Alman的文章。文章中Ben Alman 已经解释得很清楚了，希望定义自执行函数式常见的语法错误有两种：
1">
<meta property="og:updated_time" content="2017-02-17T06:30:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Javascript知识点：IIFE - 立即调用函数">
<meta name="twitter:description" content="Immediately-invoked Function Expression（IIFE，立即调用函数），简单的理解就是定义完成函数之后立即执行。因此有时候也会被称为“自执行的匿名函数”（self-executing anonymous function）。
IIFE的叫法最早见于Ben Alman的文章。文章中Ben Alman 已经解释得很清楚了，希望定义自执行函数式常见的语法错误有两种：
1">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"post","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://jiji262.github.io/2016/04/25/2016-04-08-Javascript-IIFE/"/>





  <title> Javascript知识点：IIFE - 立即调用函数 | 令狐葱@前端笔记 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?0fd825270d7f51597f963010828c65b8";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-post page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">令狐葱@前端笔记</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle"></p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://jiji262.github.io/2016/04/25/2016-04-08-Javascript-IIFE/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="令狐葱">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/avatar.gif">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="令狐葱@前端笔记">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="令狐葱@前端笔记" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Javascript知识点：IIFE - 立即调用函数
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2016-04-25T20:10:00+08:00">
                2016-04-25
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2016/04/25/2016-04-08-Javascript-IIFE/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/04/25/2016-04-08-Javascript-IIFE/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Immediately-invoked Function Expression（IIFE，立即调用函数），简单的理解就是定义完成函数之后立即执行。因此有时候也会被称为“自执行的匿名函数”（self-executing anonymous function）。</p>
<p>IIFE的叫法最早见于Ben Alman的文章。文章中Ben Alman 已经解释得很清楚了，希望定义自执行函数式常见的语法错误有两种：</p>
<p>1) <code>function (){ }()</code></p>
<p>期望是立即调用一个匿名函数表达式，结果是进行了函数声明，函数声明必须要有标识符做为函数名称。</p>
<p>2) <code>function g(){ }()</code></p>
<p>期望是立即调用一个具名函数表达式，结果是声明了函数 g。末尾的括号作为分组运算符，必须要提供表达式做为参数。<br>所以那些匿名函数附近使用括号或一些一元运算符的惯用法，就是来引导解析器，指明运算符附近是一个表达式。</p>
<p>按照这个理解，可以举出五类，超过十几种的让匿名函数表达式立即调用的写法：</p>
<p><strong>1）使用括号</strong></p>
<pre><code>( function() {}() );
( function() {} )();
[ function() {}() ];
</code></pre><p><strong>2）使用一元操作符</strong></p>
<pre><code>~ function() {}();
! function() {}();
+ function() {}();
- function() {}();
</code></pre><p><strong>3）使用void等操作符</strong></p>
<pre><code>delete function() {}();
typeof function() {}();
void function() {}();
</code></pre><p><strong>4）使用表达式</strong></p>
<pre><code>var i = function(){ return 10; }();
true &amp;&amp; function(){ /* code */ }();
0, function(){ /* code */ }();
1 ^ function() {}();
1 &gt; function() {}();
</code></pre><p><strong>5）使用new关键字</strong></p>
<pre><code>new function(){ /* code */ }

new function(){ /* code */ }() //如果没有参数，最后的()就不需要了
</code></pre><a id="more"></a>
<p>但是总体来说，比较常见的是如下三种写法：</p>
<pre><code>// Crockford&apos;s preference - parens on the inside
(function() {
  console.log(&apos;Welcome to the Internet. Please follow me.&apos;);
}()); 

(function() {
  console.log(&apos;Welcome to the Internet. Please follow me.&apos;); 

})(); 

!function() {

  console.log(&apos;Welcome to the Internet. Please follow me.&apos;); 

}(); 
</code></pre><p>其实讨论IIFE的多少种写法多少和研究茴香豆的“茴”字有几种写法一样无聊，但其实不无用处，至少在阅读别人的代码时见到这样的写法不至于不知所云，抑或可以拿出去和小伙伴们装装，顿时觉得逼格提升不少。</p>
<p><em>参考资料：</em></p>
<p><a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" target="_blank" rel="external">http://benalman.com/news/2010/11/immediately-invoked-function-expression/</a><br>（<a href="http://www.cnblogs.com/TomXu/archive/2011/12/31/2289423.html" target="_blank" rel="external">中文译文</a>）</p>
<p><a href="http://www.elijahmanor.com/angry-birds-of-javascript-red-bird-iife/" target="_blank" rel="external">http://www.elijahmanor.com/angry-birds-of-javascript-red-bird-iife/</a><br>（<a href="http://nuysoft.com/2013/04/15/angry-birds-of-javascript-red-bird-iife/Immediately-invoked%20Function%20Expression" target="_blank" rel="external">中文译文</a>）</p>
<p><a href="http://www.zhihu.com/question/20249179" target="_blank" rel="external">http://www.zhihu.com/question/20249179</a></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechatmp.jpg" alt="令狐葱 wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎您扫一扫上面的二维码，订阅我的微信公众号！</div>
</div>


      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div></div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/uploads/wechatpay.png" alt="令狐葱 WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/uploads/alipaypay.png" alt="令狐葱 Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/前端/" rel="tag"># 前端</a>
          
            <a href="/tags/前端基础/" rel="tag"># 前端基础</a>
          
            <a href="/tags/IIFE/" rel="tag"># IIFE</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/04/20/setup-Shadowsocks-on-ubuntu-1604/" rel="next" title=" 科学上网:ubuntu 16.04服务器上搭建Shadowsocks服务">
                <i class="fa fa-chevron-left"></i>  科学上网:ubuntu 16.04服务器上搭建Shadowsocks服务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/04/29/create-your-own-react-boilerplate/" rel="prev" title="手把手教你基于ES6架构自己的React Boilerplate项目">
                手把手教你基于ES6架构自己的React Boilerplate项目 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/04/25/2016-04-08-Javascript-IIFE/"
           data-title="Javascript知识点：IIFE - 立即调用函数" data-url="http://jiji262.github.io/2016/04/25/2016-04-08-Javascript-IIFE/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="令狐葱" />
          <p class="site-author-name" itemprop="name">令狐葱</p>
           
              <p class="site-description motion-element" itemprop="description">去留无意，闲看庭前花开花落；宠辱不惊，漫随天外云卷云舒。</p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">28</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/jiji262" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/linghucong" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/jiji262" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">令狐葱</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"jiji262"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  













  
  

  

  

  

  


</body>
</html>
